﻿using AutoMapper;
using HRSolutionSystem.Application.Contracts.Logging;
using HRSolutionSystem.Application.Contracts.Persistence;
using HRSolutionSystem.Application.Exceptions;
using MediatR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HRSolutionSystem.Application.Features.LeaveType.Queries.GetAllLeaveTypes
{
    public class GetLeaveTypeQueryHandler : IRequestHandler<GetLeaveTypeQuery,
        List<LeaveTypeDto>>
    {
        private readonly IMapper _mapper;
        private readonly ILeaveTypeRepository _leaveTypeRepository;
        private readonly IAppLogger<GetLeaveTypeQueryHandler> _logger;

        public GetLeaveTypeQueryHandler(IMapper mapper,
            ILeaveTypeRepository leaveTypeRepository,
            IAppLogger<GetLeaveTypeQueryHandler> logger) 
        {
            this._mapper = mapper;
            this._leaveTypeRepository = leaveTypeRepository;
            this._logger = logger;
        }
        public async Task<List<LeaveTypeDto>> Handle(GetLeaveTypeQuery request, CancellationToken cancellationToken)
        {
            //1 Query the database
            var leaveTypes = await _leaveTypeRepository.GetAsync();
            if (leaveTypes == null)
            {
                throw new NotFoundException(nameof(leaveTypes), request);
            }
            //2 convert data objects to DTO objects
            var data = _mapper.Map<List<LeaveTypeDto>>(leaveTypes);
            //3 return list of DTO object
            _logger.LogInformation("Leave types were retrieved successfully!");
            return data;
        }
    }
}
